package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.CouponRecordMessage;
import net.xdclass.model.ProductMessage;
import net.xdclass.service.ProductService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.stock_release_queue}")
public class ProductStockMQListener {

    @Autowired
    private ProductService productService;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 消费
     *
     * @param productMessage
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void releaseProductReocrd(ProductMessage productMessage, Message message, Channel channel) throws IOException {
        log.info("监听到消息:releaseProductReocrd消息内容:{}", productMessage);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        boolean bl = productService.releaseProductStock(productMessage);
        try {
            if (bl) {
                channel.basicAck(deliveryTag, false);
            } else {
                log.error("释放商品库存失败 flag=false,{}", productMessage);
                channel.basicReject(deliveryTag, true);
            }
        } catch (IOException e) {
            log.error("释放商品库存记录异常:{}.msg:{}", e, productMessage);
            channel.basicReject(deliveryTag, true);
        }
    }
}
